<template>
    <a-modal :keyboard="false" :maskClosable="false" title="默认接单人" :open="visible" :width="700" :confirmLoading="loading" centered @ok="handleSubmit" @cancel="handleCancel">
        <a-form ref="formRef" :model="modelRef" layout="vertical">
            <a-row :gutter="16" type="flex" justify="start">
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item
                        label="项目名称"
                        name="projectCodes"
                        :rules="{
                            required: true,
                            message: '请选择项目名称',
                            trigger: 'change',
                        }"
                    >
                        <a-cascader
                            v-model:value="modelRef.projectCodes"
                            :options="treeData"
                            :field-names="{
                                children: 'children',
                                label: 'name',
                                value: 'code',
                            }"
                            placeholder="项目名称"
                            @change="handleCascaderChange"
                        >
                            <template #displayRender="{ labels, selectedOptions }">
                                <span v-for="(label, index) in labels" :key="selectedOptions[index].value">
                                    {{ index + 1 == labels.length ? label : '' }}
                                </span>
                            </template>
                        </a-cascader>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item
                        label="条线"
                        name="tx"
                        :rules="{
                            required: true,
                            message: '请选择条线',
                            trigger: 'change',
                        }"
                    >
                        <a-select
                            v-model:value="modelRef.tx"
                            :options="txLists"
                            style="width: 100%"
                            :field-names="{
                                label: 'name',
                                value: 'name',
                            }"
                            @change="txChange"
                        ></a-select>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="24">
                    <a-row :gutter="16" v-for="(item, index) in modelRef.users" :key="index">
                        <a-col :xs="24" :sm="24" :md="12">
                            <a-form-item
                                label="默认接单人"
                                :name="['users', index, 'userId']"
                                :rules="{
                                    required: true,
                                    message: '请选择接单人',
                                    trigger: 'change',
                                }"
                            >
                                <a-select
                                    v-model:value="modelRef.users[index].userId"
                                    style="width: 100%"
                                    placeholder="请选择"
                                    :options="userList"
                                    showSearch
                                    optionFilterProp="name"
                                    :field-names="{
                                        label: 'name',
                                        value: 'id',
                                    }"
                                    @change="(value, option) => userChange(value, option, index)"
                                ></a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :xs="24" :sm="24" :md="4">
                            <a-form-item
                                label="开始时间"
                                :name="['users', index, 'start']"
                                :rules="{
                                    required: true,
                                    message: '请选择',
                                    trigger: 'change',
                                }"
                            >
                                <a-select v-model:value="modelRef.users[index].start" style="width: 100%" placeholder="开始时间">
                                    <a-select-option v-for="(item, index) in timeList" :value="item.value" :key="index">{{ item.label }}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :xs="24" :sm="24" :md="4">
                            <a-form-item
                                label="结束时间"
                                :name="['users', index, 'end']"
                                :rules="{
                                    required: true,
                                    message: '请选择',
                                    trigger: 'change',
                                }"
                            >
                                <a-select v-model:value="modelRef.users[index].end" style="width: 100%" placeholder="结束时间">
                                    <a-select-option v-for="(item, index) in timeList" :value="item.value" :key="index">{{ item.label }}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :xs="24" :sm="24" :md="2">
                            <a-form-item label="操作">
                                <div style="display: flex">
                                    <a-button v-if="index == modelRef.users.length - 1" type="primary" shape="circle" @click="addUser">
                                        <plus-outlined />
                                    </a-button>
                                    <a-button v-if="modelRef.users.length > 1" type="primary" shape="circle" @click="delUser(index)">
                                        <minus-outlined />
                                    </a-button>
                                </div>
                            </a-form-item>
                        </a-col>
                        <a-col :xs="24" :sm="24" :md="2"></a-col>
                    </a-row>
                </a-col>
            </a-row>
        </a-form>
    </a-modal>
</template>

<script lang="ts">
    import type { PropType, Ref } from 'vue';
    import { defineComponent, reactive, ref, watchEffect, watch } from 'vue';
    import { Form, message } from 'ant-design-vue';
    import { createOrderPickup, updateOrderPickup, getOrderPickup } from '@/api/order/order-pickup';
    import { cloneDeep, indexOf, isEmpty, isUndefined } from 'lodash-es';
    import type { TreeProps, FormInstance } from 'ant-design-vue';
    import { queryProjectTree } from '@/api/list/project-list';
    import { txList } from '@/api/common/proline';
    import { getEmployeeList } from '@/api/list/employee-list';
    import { findTree } from 'xe-utils';
    import { PlusOutlined, MinusOutlined } from '@ant-design/icons-vue';

    const fieldNames: TreeProps['fieldNames'] = {
        children: 'children',
        title: 'name',
        key: 'code',
    };
    const timeList = [
        {
            value: 0,
            label: '0点',
        },
        {
            value: 1,
            label: '1点',
        },
        {
            value: 2,
            label: '2点',
        },
        {
            value: 3,
            label: '3点',
        },
        {
            value: 4,
            label: '4点',
        },
        {
            value: 5,
            label: '5点',
        },
        {
            value: 6,
            label: '6点',
        },
        {
            value: 7,
            label: '7点',
        },
        {
            value: 8,
            label: '8点',
        },
        {
            value: 9,
            label: '9点',
        },
        {
            value: 10,
            label: '10点',
        },
        {
            value: 11,
            label: '11点',
        },
        {
            value: 12,
            label: '12点',
        },
        {
            value: 13,
            label: '13点',
        },
        {
            value: 14,
            label: '14点',
        },
        {
            value: 15,
            label: '15点',
        },
        {
            value: 16,
            label: '16点',
        },
        {
            value: 17,
            label: '17点',
        },
        {
            value: 18,
            label: '18点',
        },
        {
            value: 19,
            label: '19点',
        },
        {
            value: 20,
            label: '20点',
        },
        {
            value: 21,
            label: '21点',
        },
        {
            value: 22,
            label: '22点',
        },
        {
            value: 23,
            label: '23点',
        },
    ];

    export default defineComponent({
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            model: {
                type: Object as PropType<any>,
                default: () => null,
            },
        },
        emits: ['cancel', 'success'],
        setup(props, { emit }) {
            const loading = ref(false);
            const options = [
                {
                    label: '户内',
                    value: '0',
                },
                {
                    label: '公区',
                    value: '1',
                },
            ];

            const typeMap = {
                '0': `报事报修`,
                '1': `投诉`,
            };
            const defaultForm = {
                projectCode: '',
                projectName: '',
                projectCodes: [],
                tx: '',
                users: [
                    {
                        userId: '',
                        nickname: '',
                        start: 8,
                        end: 20,
                    },
                    {
                        userId: '',
                        nickname: '',
                        start: 20,
                        end: 8,
                    },
                ],
            };
            const modelRef = reactive<any>(cloneDeep(defaultForm));

            const rulesRef = reactive({
                tx: [{ required: true, message: '请选择条线' }],
                projectCodes: [{ required: true, message: '请选择项目' }],
                userId: [{ required: true, message: '请选择接单人' }],
                start: [{ required: true, message: '请选择开始时间' }],
                end: [{ required: true, message: '请选择结束时间' }],
            });
            const { validateInfos, resetFields, validate } = Form.useForm(modelRef, rulesRef);

            // 记录初始值
            const initValues = reactive({});
            watch(
                () => props.visible,
                () => {
                    Object.assign(initValues, cloneDeep(props.model));
                },
            );
            const treeData: Ref<TreeProps['treeData']> = ref([]);
            watchEffect(() => {
                if (props.visible) {
                    if (!isUndefined(props.model.id)) {
                        getOrderPickup(props.model.id).then(res => {
                            Object.assign(modelRef, res.data);

                            getEmployeeLists();
                            getTxList();
                            queryProjectTree().then(res => {
                                treeData.value = [res.data as any];
                                const { nodes = [] } = findTree(treeData.value, (item: any) => item.code === props.model.projectCode);
                                modelRef.projectCodes = nodes.map(item => item.code);
                            });
                        });
                    } else {
                        getTxList();
                        queryProjectTree().then(res => {
                            treeData.value = [res.data as any];
                        });
                    }
                }
            });

            const txLists: any = ref([]);
            const getTxList = () => {
                txList().then(res => {
                    txLists.value = res.data;
                });
            };
            const userList: any = ref([]);
            // 获取员工列表
            const getEmployeeLists = () => {
                getEmployeeList({ projectCode: modelRef.projectCode }).then(res => {
                    userList.value = res.data;
                });
            };
            const handleCascaderChange = (value: any, selectedOptions: any) => {
                const select = selectedOptions[selectedOptions.length - 1];
                modelRef.projectName = select.name;
                modelRef.projectCode = select.code;
                getEmployeeLists();
                modelRef.users.map(item => {
                    item.userId = '';
                    item.nickname = '';
                });
            };
            const txChange = () => {
                // getEmployeeLists();
                // modelRef.users.map(item => {
                //     item.userId = '';
                //     item.nickname = '';
                // });
            };
            const userChange = (value, option, index) => {
                modelRef.users[index].nickname = option.name;
            };

            const addUser = () => {
                modelRef.users.push({
                    userId: '',
                    nickname: '',
                    start: null,
                    end: null,
                });
            };
            const delUser = index => {
                modelRef.users.splice(index, 1);
            };

            const handleCancel = () => {
                resetFields();
                Object.keys(modelRef).forEach(key => {
                    delete modelRef[key];
                });
                Object.assign(modelRef, cloneDeep(defaultForm));

                modelRef.status = 1;
                emit('cancel');
            };
            const formRef = ref<FormInstance>();
            const handleSubmit = async () => {
                formRef.value.validate().then(() => {
                    loading.value = true;

                    (isUndefined(modelRef.id) ? createOrderPickup : updateOrderPickup)({
                        ...(modelRef as any),
                    })
                        .then(res => {
                            if (res.code == 200) {
                                message.success('操作成功');
                                emit('success');
                                handleCancel();
                            }
                        })
                        .finally(() => {
                            loading.value = false;
                        });
                });
            };
            return {
                txChange,
                formRef,
                delUser,
                addUser,
                timeList,
                userChange,
                userList,
                handleCascaderChange,
                getEmployeeLists,
                txLists,
                treeData,
                loading,

                modelRef,
                validateInfos,
                resetFields,

                handleSubmit,
                handleCancel,

                initValues,
                fieldNames,
                typeMap,
                options,

                isEmpty,
            };
        },
        components: {
            PlusOutlined,
            MinusOutlined,
        },
    });
</script>
